package com.imddy.tweb.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.imddy.tweb.constant.Global;
import com.imddy.tweb.util.StringUtils;


public class LoginFilter implements Filter {
	
	private FilterConfig filterConfig = null;           
    private String redirectURL = null;           
    private List notCheckURLList = new ArrayList(); 


    public LoginFilter() {
        
    }

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
		Object user = httpRequest.getSession().getAttribute(Global.USER_SESSION_KEY);
		if (user == null) {
			System.out.println("尚未登录，调到登录页面");
			httpResponse.sendRedirect("/loginpage.html");
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		this.filterConfig = fConfig;
        redirectURL = filterConfig.getInitParameter("redirectURL");
        String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");
        
        if (!StringUtils.isNullOrEmpty(notCheckURLListStr)) {
        	//将字符串转化为list
        	notCheckURLList = StringUtils.spitToList(notCheckURLListStr, ";");
        }

	}
	
    /* web.xml中的filter配置
	<filter>  
    	<filter-name>CheckLoginFilter</filter-name>  
    	<filter-class>net.cnki.tpi.cms.util.CheckLoginFilter</filter-class>  
    	<init-param>  
    		<param-name>redirectURL</param-name>  
    		<param-value>/login.jsp</param-value>  
    	</init-param>  
    	<init-param>   
        	<param-name>notCheckURLList </param-name>   
         	<param-value>/error.jsp;/login.jsp</param-value>   
    	</init-param>   
 	</filter>  
 	<filter-mapping>  
    	<filter-name>CheckLoginFilter</filter-name>  
    	<url-pattern>/*</url-pattern>  
 	</filter-mapping> 
    */
}
